package de.tum.getraenke;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class SyncAdapter extends CursorAdapter {

	private final Date date;
	private static final DateFormat DF_DATE = 
			SimpleDateFormat.getDateInstance(DateFormat.MEDIUM);
	private static final DateFormat DF_TIME =
			SimpleDateFormat.getTimeInstance(DateFormat.MEDIUM);
	private LayoutInflater inflator;
	private int cName, cPacking, cSize, cAmount, cSyncOk, cLastTry;
	
	public SyncAdapter(Context context, Cursor c) {
		super(context, c);
		date = new Date();
		inflator = LayoutInflater.from(context);
		cName = c.getColumnIndex(DrinkDBHandler.DRINK_NAME);
		cPacking = c.getColumnIndex(DrinkDBHandler.DRINK_PACKING);
		cSize = c.getColumnIndex(DrinkDBHandler.DRINK_SIZE);
		cAmount = c.getColumnIndex(DrinkDBHandler.ORDER_AMOUNT);
		cSyncOk = c.getColumnIndex(DrinkDBHandler.ORDER_IS_BOOKED);
		cLastTry = c.getColumnIndex(DrinkDBHandler.ORDER_LAST_TRY);
	}
	
	@Override
	public void bindView(View view, Context context, Cursor cursor) {
		String name = cursor.getString(cName);
		String packing = cursor.getString(cPacking);
		float size = cursor.getFloat(cSize);
		int booked = cursor.getInt(cSyncOk);
		int amount = cursor.getInt(cAmount);
		long lastTry = cursor.getLong(cLastTry);
		ImageView image = (ImageView) view.findViewById(R.id.orderSyncIcon);
		if(booked == 1) {
			image.setImageResource(R.drawable.ok);			
		} else {
			image.setImageResource(R.drawable.not);
		}
		TextView productName = (TextView) view.findViewById(R.id.productName);
		TextView productPacking = (TextView) view.findViewById(R.id.productPacking);
		TextView orderAmount = (TextView) view.findViewById(R.id.orderAmount);
		TextView orderSync = (TextView) view.findViewById(R.id.orderSync);
		productName.setText(name + (size != 0.0 ? " " + String.valueOf(size) + "l" : ""));
		productPacking.setText(packing);
		orderAmount.setText(String.valueOf(amount) + " x");
		date.setTime(lastTry);
		orderSync.setText(DF_DATE.format(date) + " " + DF_TIME.format(date));
	}

	@Override
	public View newView(Context context, Cursor cursor, ViewGroup parent) {
		return inflator.inflate(R.layout.sync_text_text, null);
	}
}
